package com.libbase

import java.lang.ref.WeakReference
import kotlin.reflect.KProperty

class Weak<T : Any>(
    initializer: () -> T?,
    private val willSet: ((newValue: T?) -> Unit)?,
    private val didSet: ((oldValue: T?) -> Unit)?
) {

    private var weakReference = WeakReference<T?>(initializer())

    constructor() : this({
        null
    })

    constructor(initializer: () -> T?) : this(initializer, null, null)

    operator fun getValue(thisRef: Any?, property: KProperty<*>): T? {
        return weakReference.get()
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
        willSet?.let {
            it(value)
        }

        weakReference = WeakReference(value)

        didSet?.let {
            it(weakReference.get())
        }
    }
}